import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:study_flutter/yzhg/project/shop/config/service_url.dart';

class ShopDioUtils {
  static final String BASE_URL = serviceUrl; //base url

  //设置私有的DioUtils
  static ShopDioUtils _instance;

  Dio _dio;

  //设置全局的OptionsDioUtils.dart
  BaseOptions _baseOptions;

  static ShopDioUtils getInstance() {
    if (_instance == null) {
      _instance = new ShopDioUtils();
    }
    return _instance;
  }

  //初始化配置
  ShopDioUtils() {
    //请求参数配置
    _baseOptions = new BaseOptions(
      baseUrl: BASE_URL,
      //配置总地址      connectTimeout: 6000,
      //配置连接时间
      receiveTimeout: 6000,
      //配置超时时间
      headers: {
        //设置统一请求头
        //"testHeader": "bb"
      },
      //支持ContentType.parse("application/x-www-form-urlencoded")
      contentType: Headers.formUrlEncodedContentType,
      //表示期望以那种格式(方式)接受响应数据。接受三种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`,
      responseType: ResponseType.json,
    );

    //创建dio的实例
    _dio = new Dio(_baseOptions);
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions requestions) async {
      /*添加参数*/
    //  requestions.queryParameters["token"] = "testtoken123443423";
     // requestions.queryParameters["userId"] = "123456";
    //  print('-----请求参数--' + requestions.queryParameters.toString());
      return requestions;
    }, onResponse: (Response response) {
      //此处拦截工作在数据返回之后，可在此对dio请求的数据做二次封装或者转实体类等相关操作
      //封装  errCode,errMsg,data数据
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print("ERROR: ==========> 后端接口出现异常");
        throw Exception("后端接口出现异常");
      }
    }, onError: (DioError e) {
      if (e.type == DioErrorType.CONNECT_TIMEOUT) {
        // It occurs when url is opened timeout.
        print("ERROR: ==========> 连接超时 $e");
      } else if (e.type == DioErrorType.SEND_TIMEOUT) {
        // It occurs when url is sent timeout.
        print("ERROR: ==========> 请求超时 $e");
      } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
        //It occurs when receiving timeout
        print("ERROR: ==========> 响应超时 $e");
      } else if (e.type == DioErrorType.RESPONSE) {
        // When the server response, but with a incorrect status, such as 404, 503...
        print("ERROR: ==========> 出现异常 $e");
      } else if (e.type == DioErrorType.CANCEL) {
        // When the request is cancelled, dio will throw a error with this type.
        print("ERROR: ==========> 请求取消 $e");
      } else {
        //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
        print("ERROR: ==========> 未知错误 $e");
      }
    }));
  }

  /*
   * get请求封装
   */
  get(url, {data, options}) async {
    print('get request path ------${url}-------请求参数${data}');
    print('------------');
    Response response;
    try {
      response = await _dio.get(url, queryParameters: data, options: options);
      debugPrint('get result ---${response.data}');
    } on DioError catch (e) {
      print('请求失败---错误类型${e.type}--错误信息${e.message}');
    }
    print('请求成功===========' + response.data.toString());
    return response.data.toString();
  }

/*
 * post请求封装
 */
  post(url, {data, options}) async {
    print('post request path ------${url}-------请求参数${data}');
    Response response;
    try {
      response = await _dio.post(url, data: data, options: options);
      print('post result ---${response.data}');
    } on DioError catch (e) {
      print('请求失败---错误类型${e.type}--错误信息${e.message}');
    }
    return response.data.toString();
  }
}
